const prefix = "data-";
const attributeName = "gwdrag";
window.dragName = "";
window.dragType = "";
window.dragCom = "";
import getPageName from "../getPageName";
import {getPageNameOrVirtualPageName} from "../getPageName";
/**
 * 定义一个插件，将传入的Dom元素变为可拖拽的
 */

let containerTypeStrategy = {
    "header-container": function () {
        return "header";
    },
    "content-container": function () {
        return "content";
    },
    "footer-container": function () {
        return "footer"
    }
}
export default {
    dragName: "",
    _vue: null,
    install(Vue, options = {}) {
        let t = this;
        Vue.directive("sdrag", {
            bind(el, binding, vnode) {
                // console.log("绑定的el", el);
                //获取当前拖拽组件的类型
                let type = binding.arg;//String类型的参数
                let com = binding.value.com;
                let dragable = binding.value.dragable != undefined ? parseInt(binding.value.dragable) : 1;//是否可以拖拽：0，不能，1，能
                // console.log("binding.value.editable", binding.value.editable)
                let editable = binding.value.editable != undefined ? binding.value.editable : true;
                // console.log("是否能拖拽", dragable);
                // 获取当前组件的上下文对象
                t._vue = vnode.context;
                //获取组件的id
                t.id = binding.value.id;
                //获取真实组件的type
                if (type === "real" && t.checkoutEnvironment()) {
                    t.initHoverEvent(el, binding.value.type, binding.value.id, binding.value.focusShow, editable);
                }
                t.setAttribute(el, binding.value.id);
                //初始化拖拽事件
                if (dragable === 1 && t.checkoutEnvironment()) {
                    t.initComponentDragEvent(el, type, com);
                }

            },
            componentUpdated(el, binding) {
                el.setAttribute("data-gwdrag", binding.value.id);
                let type = binding.arg;//String类型的参数
                let editable = binding.value.editable != undefined ? binding.value.editable : true;
                if (type === "real" && t.checkoutEnvironment()) {
                    t.initHoverEvent(el, binding.value.type, binding.value.id, binding.value.focusShow, editable);
                }
                // console.log("单个el更新完毕");
            }
        })
    },
    setAttribute(dom, value) {
        if (dom.getAttribute(prefix + attributeName)) {
            return dom.getAttribute(prefix + attributeName);
        }
        return dom.setAttribute(prefix + attributeName, value || this.createName());
    },
    //命名规范
    createName() {
        this.dragName = "gw" + parseInt(Math.random() * 10000);
        return this.dragName;
    },
    //初始化拖拽事件
    initComponentDragEvent(dom, type, com) {
        dom.setAttribute("draggable", "true");
        dom.ondragstart = (event) => {
            // console.log(event);
            // console.log("拖拽开始");
            window.dragName = this.setAttribute(event.target);
            window.dragType = type;
            window.dragCom = com;
            // console.log(this._vue.$store.getters.getStyleComponentsCoverState);
            //开始拖拽的时候隐藏遮罩层和组件列表
            if (window.innerWidth <= 1366) {
                this._vue.$store.commit("setStyleComponentsCoverState", false);
                this._vue.$store.commit("setStyleComponentsState", "hide");
            }
        }
        dom.ondragend = () => {
            // console.log("拖拽结束");
            // console.log(window.dragName);
        }

    },
    //初始化移入hover事件
    initEditEvent(dom, type, id, focusShow, editable) {
        // console.log("移入dom", dom);
        //鼠标hover操作，显示虚框
        let className = dom.getAttribute("class");
        //判断该dom的定位方式，如果是static则添加该类，否则不添加
        // console.log("鼠标移入的时候获取dom的poisition", window.getComputedStyle(dom, null).position);
        if (window.getComputedStyle(dom, null).position === "static") {
            if (className) {
                // console.log("鼠标移入的时候获取dom的class", className);
                className += " sdrag-edit";
            } else {
                className = "sdrag-edit";
            }
            dom.setAttribute("class", className);

        }
        this.createHoverEditBox(dom, type, id, focusShow, editable);
    },
    //创建编辑虚线框
    createHoverEditBox(dom, type, id, focusShow, editable) {
        // console.log("创建编辑虚线框用到的dom", dom);
        let box = document.createElement("div");
        box.setAttribute("class", "hover-edit-box");
        let height = dom.offsetHeight + 4;
        let width = dom.offsetWidth;
        let left = dom.getBoundingClientRect().left - 2;
        // let top = dom.getBoundingClientRect().top + document.querySelector(".home-container").scrollTop - 60 - 2;
        let top = -2;
        // console.log("focusShow", focusShow);
        // if (focusShow || focusShow === "true") {
        if (true) {
            top = 26;
        }
        let style = `position: absolute;width: ${width}px;height: 0;top: ${top}px;z-index: 99999;`
        box.style = style;
        //编辑按钮和删除按钮
        let btnBox = document.createElement("div");
        btnBox.setAttribute("class", "sdrag-box-style");
        let editBtn = document.createElement("span");
        editBtn.setAttribute("class", "sdrag-blue-btn");
        //初始化编辑按钮的点击事件
        // console.log("初始化编辑按钮的点击事件", editable);
        if (editable) {
            this.initEditBtnClickEvent(editBtn, type, id);
        } else {
            editBtn.setAttribute("style", "cursor: not-allowed");
        }
        editBtn.innerHTML = "编辑";
        let deleteBtn = document.createElement("span");
        deleteBtn.setAttribute("class", "sdrag-blue-btn");
        //如果该dom是header或者footer层级下面的，则禁用删除按钮
        if (this.getContainerType(dom) === "content") {
            // console.log("初始化删除按钮的事件");
            //初始化删除按钮的事件
            this.initDeleteBtnClickEvent(deleteBtn, type, id);
        } else {
            deleteBtn.setAttribute("style", "cursor: not-allowed");
        }
        deleteBtn.innerHTML = "删除";
        //加一个虚线框
        // let borderBox = document.createElement("div");
        // borderBox.setAttribute("class", "sdrag-border-box");
        // borderBox.style = `height: ${height - 4}px;
        //     position: absolute;
        //     top: ${-top}px;
        //     left: 0;
        //     width: 100%;
        //     border: 2px dashed #409eff;
        // `;
        dom.style.border = "2px dashed #409eff";
        // dom.style.boxSizing = "border-box";
        // dom.style.transition = "border 0.3s";
        //添加一个可以插掉按钮的按钮
        let closeBtnBox = document.createElement("img");
        closeBtnBox.src = "static/image/btn_01.png";
        closeBtnBox.style.width = "15px";
        closeBtnBox.style.height = "15px";
        closeBtnBox.style.marginRight = "3px";
        //初始化叉掉按钮的按钮的事件
        this.initCloseBtnBoxEvent(closeBtnBox);
        btnBox.appendChild(editBtn);
        btnBox.appendChild(deleteBtn);
        btnBox.appendChild(closeBtnBox);
        // let btnBoxStyle = `position: fixed;left: ${left}px;top: ${top}px;z-index: 2;`;
        // btnBox.style = btnBoxStyle;
        box.appendChild(btnBox);
        // box.appendChild(borderBox);
        dom.appendChild(box);
        // document.body.appendChild(box);
        // dom.appendChild(btnBox);
    },
    // 触发移出操作
    removeHoverBox(dom) {
        let className = dom.getAttribute("class");
        if (className) {
            className = className.split(" ");
            for (let i = 0; i < className.length; i++) {
                if (className[i] === "sdrag-edit") {
                    className.splice(i, 1);
                    break;
                }
            }
            className = className.join(" ");
            dom.setAttribute("class", className);
        }
        dom.style.border = "unset";
        dom.removeChild(dom.querySelector(".hover-edit-box"));
        // document.body.removeChild(document.body.querySelector(".hover-edit-box"));
        // dom.removeChild(dom.querySelector(".sdrag-box-style"));
    },
    //初始化hover事件
    initHoverEvent(dom, type, id, focusShow = false, editable = true) {
        dom.onmouseenter = () => {
            this.initEditEvent(dom, type, id, focusShow, editable);
        }
        dom.onmouseleave = () => {
            this.removeHoverBox(dom);
        }
    },
    //初始化编辑按钮的点击事件
    initEditBtnClickEvent(dom, type, id) {

        dom.onclick = () => {
            let obj = {
                type,
                id
            }
            //点击编辑按钮的时候有两种情况不会触发判断
            //一种是重复点击当前组件的编辑按钮
            //第二种是点击新增组件的编辑按钮
            //做以上规避才是合理的
            let editConfigVuex = this._vue.$store.getters.editConfig;
            if (id === editConfigVuex.id && type === editConfigVuex.type) {
                return;
            }
            this._vue.$store.dispatch({
                type: "changeEditItem",
                obj,
                context: this._vue
            });
        }
    },
    initDeleteBtnClickEvent(dom, type, id) {
        // console.log("这是要删除的id", id);
        dom.onclick = () => {
            let obj = {
                type: "",
                id: ""
            }
            //改变编辑区域的显示状态
            this._vue.$store.commit("setEditConfigVuex", obj);
            let domTree = this._vue.$store.getters.getDomTree[getPageNameOrVirtualPageName()];
            //如果是NewZone，还要删除对应的TabHeader里的item
            if (getPageNameOrVirtualPageName() === "NewThematicActivities" && type === "NewZone") {
                for (let item of domTree.header) {
                    // console.log("item", item);
                    //删除专题活动页面的标题图片组件时，删除TabHeader里对应的item
                    if (item.type === "TabHead") {
                        //如果TabHeader里没有对应的item，直接跳出循环
                        if (!item.config || !item.config.pages || !item.config.pages.length) {
                            // console.log("如果TabHeader里没有对应的item，直接跳出循环");
                            break;
                        }
                        // console.log("继续执行");
                        let isContinued = true;
                        for (let i = 0; i < item.config.pages.length; i++) {
                            if (item.config.pages[i].comId === id) {
                                //找到了对应的jumpItem
                                // console.log("找到了对应的jumpItem");
                                item.config.pages.splice(i, 1);
                                isContinued = false;
                                break;
                            }
                            // console.log("继续执行x2");
                        }
                        // console.log("继续执行x3");
                        if (!isContinued) {
                            break;
                        }

                        // console.log("继续执行x4");
                    }
                }
            }
            let area = "content";
            let targetIndex;
            //从虚拟domTree中删除对应的虚拟dom
            for (let i = 0; i < domTree[area].length; i++) {
                if (domTree[area][i].id === id) {
                    console.log("找到对应的要删除的id", domTree[area][i].id);
                    targetIndex = domTree[area][i].index;
                    domTree[area].splice(i, 1);
                    break;
                }
            }
            //domTree中的dom顺序进行调整
            domTree[area].forEach(item => {
                //小于targetIndex的顺序不变
                //大于targetIndex的顺序减一
                if (item.index > targetIndex) {
                    item.index -= 1;
                }
            });
            //更新虚拟domTree
            this._vue.$store.commit("setDomTree", domTree);

        }


    },
    //初始化叉掉按钮的按钮的事件
    initCloseBtnBoxEvent(dom) {
        dom.onclick = () => {
            dom.parentNode.style.display = "none";
        }
    },
    //获取父节点的container类型
    getContainerType(dom) {
        let parentNode = dom.parentNode;
        return containerTypeStrategy[parentNode.getAttribute("id")]();
    },
    //检查当前环境
    checkoutEnvironment() {
        // console.log("0000000000000000000000000", window.environment);
        if (window.environment === "production") {
            return false;
        } else if (window.environment === "edit") {
            return true;
        }
    }

}

